package flca.osm.perst.util;

import org.garret.perst.Storage;
import org.garret.perst.StorageFactory;

import flca.osm.perst.VoiceNavConstants;
import flca.osm.perst.model.IntersectRootClass;
import flca.osm.perst.model.PRootClass;

public class DbHelper implements VoiceNavConstants
{
	private static DbHelper sInstance;

	public static DbHelper getInstance()
	{
		if (sInstance == null) {
			sInstance = new DbHelper();
		}
		return sInstance;
	}

	//-------------------------------------------------
	private Storage dbInput;
	private PRootClass osmRoot;
	private Storage dbOutput;
	private IntersectRootClass intersectRoot;

	private DbHelper()
	{
		initialize();
	}

	private void initialize()
	{
		initOsmDb();
		initIntersectDb();

	}

	private void initOsmDb() {
		if (dbInput == null) {
			dbInput = StorageFactory.getInstance().createStorage();
			dbInput.open(getInputDbsName(), POOL_SIZE);
		}

		osmRoot = (PRootClass) dbInput.getRoot(); // get storage root
		if (osmRoot == null) { 
            osmRoot = new PRootClass(dbInput); // create root object
            dbInput.setRoot(osmRoot); // register root object
        }
	}

	private void initIntersectDb() {
		if (dbOutput == null) {
			dbOutput = StorageFactory.getInstance().createStorage();
			dbOutput.open(getOutputDbsName(), POOL_SIZE);
		}

		intersectRoot = (IntersectRootClass) dbOutput.getRoot(); // get storage root
		if (intersectRoot == null) { 
			intersectRoot = new IntersectRootClass(dbOutput); // create root object
            dbOutput.setRoot(intersectRoot); // register root object
        }
	}

	public PRootClass getOsmRoot() {
		return osmRoot;
	}

	public IntersectRootClass getInterSectRoot() {
		return intersectRoot;
	}

	public void cleanup() 
	{
		try {
			if (dbInput != null) {
				dbInput.close();
			}
			if (dbOutput != null) {
				dbOutput.close();
			}
			System.out.println("done!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private String getInputDbsName()
	{
		if (System.getProperty("os.name").toLowerCase().startsWith("l")) {
			return "/home/robin/temp/output/perst-osm.db";
		} else {
			return "c:/temp/log/perst-osm.db"; // TODO
		}
	}

	private String getOutputDbsName()
	{
		if (System.getProperty("os.name").toLowerCase().startsWith("l")) {
			return "/home/robin/temp/output/perst-intersections.db"; // TODO
		} else {
			return "c:/temp/log/perst-intersections.db"; // TODO
		}
	}
}
